package com.hunttown.mes.manage.service;

import com.hunttown.mes.rpc.domain.enums.pay.PayStatusEnum;
import com.hunttown.mes.rpc.domain.enums.pay.RechargeTypeEnum;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.rpc.api.TransportUserCardLogRpcService;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDTO;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDetailDTO;
import com.hunttown.mes.rpc.domain.TransportUserCardLogDTO;
import com.hunttown.mes.rpc.domain.query.TransportUserCardLogDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportTableChineseEnglishDetailDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import java.math.BigDecimal;
import java.util.*;

/**
 * created by wangjunfu on 2020-06-06 11:28:33
 */
@Service
public class TransportUserCardLogManageService {

    private final static Logger logger = LoggerFactory.getLogger(TransportUserCardLogManageService.class);

    private final TransportUserCardLogRpcService rpcService;
    private final TransportTableChineseEnglishManageService englishService;
    private final TransportTableChineseEnglishDetailManageService englishDetailService;
    private final AnalysisManageManageService manageService;

    @Autowired
    public TransportUserCardLogManageService(TransportUserCardLogRpcService rpcService, TransportTableChineseEnglishManageService englishService, TransportTableChineseEnglishDetailManageService englishDetailService, AnalysisManageManageService manageService) {
        this.rpcService = rpcService;
        this.englishService = englishService;
        this.englishDetailService = englishDetailService;
        this.manageService = manageService;
    }

    /**
     * 新增（简单）
     *
     * @param recordId    计费日志记录ID
     * @param userId      用户ID
     * @param cardId      卡ID
     * @param cardNo      卡号
     * @param meterNumber 表号，当作订单号来使用
     * @param frontAmount 交易前金额
     * @param amount      交易金额
     * @param lastNum     起数
     * @param thisNum     止数
     * @param dSign       类型：1峰/2谷/3平/4尖
     * @param remark      备注
     * @return ID
     */
    public Integer insertSimple(
            Integer recordId,
            Integer userId,
            String meterNumber,
            Integer cardId,
            String cardNo,
            BigDecimal frontAmount,
            BigDecimal amount,
            BigDecimal lastNum,
            BigDecimal thisNum,
            Integer dSign,
            String remark
    ) {
        Date defaultDate = DateConvertUtils.strToDate("1990-01-01");

        TransportUserCardLogDTO dto = new TransportUserCardLogDTO();
        dto.setTableId(138);
        dto.setRecordId(recordId);
        dto.setUserId(userId);
        dto.setCardId(cardId);
        dto.setCardNo(cardNo);
        dto.setCardType(1);
        dto.setStartTime(defaultDate);
        dto.setEndTime(defaultDate);
        dto.setOrderId(meterNumber);
        dto.setTradingNo("");
        dto.setRechargeType(RechargeTypeEnum.LIFE.getKey());
        dto.setFrontAmount(frontAmount);
        dto.setRechargeAmount(amount);
        dto.setRechargeRate(BigDecimal.ZERO);
        dto.setRateAmount(BigDecimal.ZERO);
        dto.setInvoiceNo("");
        dto.setFrontTimes(0);
        dto.setTimes(0);
        dto.setAppId("");
        dto.setPayCompay(0);
        dto.setMchId("");
        dto.setTradeType("");
        dto.setInvoiceType(0);
        dto.setTradeBody(remark + "：" + new BigDecimal(amount.toString()).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue() + "元");
        dto.setPreTradeTime(defaultDate);
        dto.setPreRequestUrl("");
        dto.setPrePayId("");
        dto.setPreCodUrl("");
        dto.setPreReturnCode("");
        dto.setPreReturnMsg("");
        dto.setRequestUrl("");
        dto.setNotifyUrl("");
        dto.setTradeTime(new Date());
        dto.setReturnCode("");
        dto.setReturnMsg("");
        dto.setNotifyTime(defaultDate);
        dto.setNotifyCode("");
        dto.setNotifyMsg("");
        dto.setLastNum(lastNum);
        dto.setThisNum(thisNum);
        dto.setUseNum(thisNum.subtract(lastNum));
        dto.setdSign(dSign);
        dto.setRemark(remark);
        dto.setOpIp("");
        dto.setBrowser("");
        dto.setStatus(PayStatusEnum.SUCCESS.getKey());
        dto.setAdminId(1);
        dto.setCreateTime(new Date());
        dto.setStopFlag(0);
        dto.setDeleteFlag(0);
        dto = insert(dto);

        if (dto != null) {
            return dto.getId();
        } else {
            return 0;
        }
    }

    // 新增
    public TransportUserCardLogDTO insert(TransportUserCardLogDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(TransportUserCardLogDTO objDTO) {
        return rpcService.updateInfoById(objDTO);
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(TransportUserCardLogDTOQuery objDTOQuery) {
        return rpcService.updateInfoByQuery(objDTOQuery);
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        return rpcService.deleteById(id);
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        TransportUserCardLogDTOQuery query = new TransportUserCardLogDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        return rpcService.updateInfoByQuery(query);
    }

    // 通过ID获取
    public TransportUserCardLogDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public TransportUserCardLogDTO getByQuery(TransportUserCardLogDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<TransportUserCardLogDTO> getForPage(TransportUserCardLogDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        TransportUserCardLogDTO obj = new TransportUserCardLogDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        return updateInfoById(obj);
    }

    //计算某个设备，一天的总费用
    public Float computeTotalAmount(TransportUserCardLogDTOQuery objDTOQuery) {
        return rpcService.computeTotalAmount(objDTOQuery);
    }

    //region 数据查看

    /**
     * 组装实体信息为前台可展示的格式
     * 可做定制化的配置
     * 存放位置：各业务的Service中
     *
     * @param model     Sevelet Model
     * @param tableName 数据库表名
     * @param obj       对象
     * @return
     */
    public Model assembleObjInfo(Model model, String tableName, TransportUserCardLogDTO obj) {

        // 结果集返回一个map
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

        // 显示标题
        String showTitle = "详情";

        // 获取数据库中英文对照表主表信息
        TransportTableChineseEnglishDTO englishDTO = englishService.getByTableName(tableName);

        if (obj == null || englishDTO == null) {
            map.put("没有查询到数据！", "");
        } else {
            Map<String, Object> origin_map = GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(obj), TransportUserCardLogDTO.class);

            if (origin_map != null) {
                // 根据表ID（tableId）获取表字段信息
                TransportTableChineseEnglishDetailDTOQuery query = new TransportTableChineseEnglishDetailDTOQuery();
                query.setTableId(englishDTO.getId());
                query.setDeleteFlag(0);
                query.setPageSize(1000);
                Page<TransportTableChineseEnglishDetailDTO> detailPage = englishDetailService.getForPage(query);

                if (detailPage != null && detailPage.getItems().size() > 0) {
                    Object value;
                    String newfield;
                    for (TransportTableChineseEnglishDetailDTO item : detailPage.getItems()) {
                        if (item.getFrontShow() == 1) {
                            newfield = GeneralUtils.standardFields(item.getFieldName());
                            value = origin_map.get(newfield);
                            if (item.getFieldType().toUpperCase().equals("TIMESTAMP")) {
                                map.put(item.getFieldNameCn(), DateConvertUtils.cstToShortStrDate(value.toString()));
                            } else {

                                if (value == null || StringUtils.isBlank(value.toString())) {
                                    map.put(item.getFieldNameCn(), "--");
                                    continue;
                                }

                                //region 开始个性化设置
                                if (newfield.equals("adminId")) { //创建人
                                    value = manageService.getNickNameFromCache(Integer.valueOf(value.toString()));
                                }
                                if (newfield.equals("stopFlag")) { //启停用状态
                                    value = value.equals(0) ? "启用" : "停用";
                                }
                                //endregion

                                map.put(item.getFieldNameCn(), value.toString());
                            }
                        }
                    }
                }
            }
        }

        model.addAttribute("showTitle", showTitle);
        model.addAttribute("showResult", map);

        return model;
    }

    //endregion
}